
/***********************************************************************
 * Save class
 * 
 * Implements the 'save' command
 *
 * Signature:
 *  public static Orbit create ();
 *  public String name ();
 *  public boolean execute (String[] arguments);
 ***********************************************************************/

import org.json.*;
import java.io.*;

/**
 * Save:
 * @author Dan & Adam
 */
public class Save extends Command {

  /**
   * Constructor:
   */
  protected Save () {
    super("save");
  }

  /**
   * Creator:
   * @return
   */
  public static Save create () {
    return new Save();
  }
  
  /**
   * SaveGameState: Saves the game to the specified file.
   * @param filename
   * @return
   */
  private boolean saveGameState(String filename) {
    try {
      // Connect a print stream to an output stream.
      PrintStream p = new PrintStream(new FileOutputStream(filename));
      // Print the JSON saved game to file.
      p.print(SpaceGame.toJSONString());
      // Close the file.
      p.close();
      System.out.println("Game Saved To File: " + filename);
    } catch (Exception e) {
      System.err.println("Error Writing To File");
    }
    return true;
  }
  
  /**
   * FileExists checks if a file exists.
   * @param filename
   * @return
   */
  private boolean fileExists(String filename) {
    boolean exists = new File(filename).exists();
    return exists;
  }
  
  /* (non-Javadoc)
   * @see Command#execute(java.lang.String[])
   */
  public boolean execute(String[] args) {
    if (args.length != 2 && args.length != 3) {
      System.out.println("Incorrect Usage, Try 'save <savefilename> [-force]' Args length"+ args.length);
    } else if (!fileExists(args[1])) {
      saveGameState(args[1]);
    } else if (args.length == 2) {
      System.out.println("File Already Exists: " + args[1] + 
                         "Try typing 'save <savefilename> -force' to force it to save.");
    } else if (args[2].equals("-f") || args[2].equals("-force")){
      saveGameState(args[1]);
    }
    return false;
  }
}
